package com.lightboat.web.controller.tool;

import cn.hutool.core.lang.Opt;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lightboat.common.core.controller.BaseController;
import com.lightboat.common.core.domain.R;
import com.lightboat.common.utils.StringUtils;
import com.lightboat.common.utils.spring.SpringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * swagger 用户测试方法
 *
 * @author lightboat
 */
@Tag(name = "用户信息管理")
@RestController
@RequestMapping("/test/user")
public class TestController extends BaseController {

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    private final static Map<Integer, UserEntity> users = new LinkedHashMap<Integer, UserEntity>();

    {
        users.put(1, new UserEntity(1, "admin", "admin123", "15888888888"));
        users.put(2, new UserEntity(2, "ry", "admin123", "15666666666"));
    }

    @Operation(summary = "获取用户列表")
    @GetMapping("/list")
    public R<List<UserEntity>> userList() {
        List<UserEntity> userList = new ArrayList<UserEntity>(users.values());
        return R.ok(userList);
    }

    @Operation(summary = "获取用户详细")
    @GetMapping("/{userId}")
    public R<UserEntity> getUser(@PathVariable(name = "userId")
                                 Integer userId) {
        if (!users.isEmpty() && users.containsKey(userId)) {
            return R.ok(users.get(userId));
        } else {
            return R.fail("用户不存在");
        }
    }

    @Operation(summary = "新增用户")
    @PostMapping("/save")
    public R<String> save(UserEntity user) {
        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
            return R.fail("用户ID不能为空");
        }
        users.put(user.getUserId(), user);
        return R.ok();
    }

    @Operation(summary = "更新用户")
    @PutMapping("/update")
    public R<String> update(@RequestBody
                            UserEntity user) {
        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
            return R.fail("用户ID不能为空");
        }
        if (users.isEmpty() || !users.containsKey(user.getUserId())) {
            return R.fail("用户不存在");
        }
        users.remove(user.getUserId());
        users.put(user.getUserId(), user);
        return R.ok();
    }

    @Operation(summary = "删除用户信息")
    @DeleteMapping("/{userId}")
    public R<String> delete(@PathVariable(name = "userId")
                            Integer userId) {
        if (!users.isEmpty() && users.containsKey(userId)) {
            users.remove(userId);
            return R.ok();
        } else {
            return R.fail("用户不存在");
        }
    }

    @Operation(summary = "测试获取接口权限")
    @GetMapping("/getInterface/permissions")
    public R<Map<String,Map<String,Object>>> getInterface() {
        Map<String, Map<String, Object>> controllerMaps = Maps.newHashMap();

        Map<String, BaseController> controllerMap = SpringUtils.getBeansOfType(BaseController.class);

        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();



        for (Map.Entry<String, BaseController> entry : controllerMap.entrySet()) {
            Map<String,Object> map = new LinkedHashMap<>();
            BaseController controller = entry.getValue();
            Class<? extends BaseController> aClass = controller.getClass();
            Tag tag = AnnotationUtils.findAnnotation(aClass, Tag.class);
            map.put("title",Opt.ofNullable(tag).map(Tag::name).orElse(aClass.getName()));
            List<Map<@Nullable String, @Nullable String>> methodMaps = Lists.newArrayList();
            for (Method method : aClass.getMethods()) {
                Map<@Nullable String, @Nullable String> methodMap = Maps.newHashMap();
                Operation operation = AnnotationUtils.findAnnotation(method, Operation.class);
                PreAuthorize preAuthorize = AnnotationUtils.findAnnotation(method, PreAuthorize.class);
                if (preAuthorize == null) {
                    continue;
                }
                String value = preAuthorize.value();
                String perm = value.replaceAll(".*\\('([^']+)'\\).*", "$1");
                String summary = Opt.ofNullable(operation).map(Operation::summary).orElse(method.getName());
                methodMap.put("apiName",summary);
                methodMap.put("permission",perm);
                methodMaps.add(methodMap);
            }

            map.put("apis",methodMaps);
            controllerMaps.put(entry.getKey(),map);
        }
        return R.ok(controllerMaps);
    }
}

@Schema(description = "用户实体")
class UserEntity {
    @Schema(title = "用户ID")
    private Integer userId;

    @Schema(title = "用户名称")
    private String username;

    @Schema(title = "用户密码")
    private String password;

    @Schema(title = "用户手机")
    private String mobile;

    public UserEntity() {

    }

    public UserEntity(Integer userId, String username, String password, String mobile) {
        this.userId = userId;
        this.username = username;
        this.password = password;
        this.mobile = mobile;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}
